package com.cssl.message;

import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class MessageImpl implements IMessage{
    @Resource
    private RabbitTemplate rabbitTemplate;

    private void sendMessage(String exchange,String routingKey,Object msg){
        rabbitTemplate.convertAndSend(exchange,routingKey,msg);
    }

    /**
     * 扣减库存
     * @param map
     */
    @Override
    public void reduceInventory(Map<Integer,Integer> map) {
        this.sendMessage("inventory","kc",map);
    }

    /**
     * 发延时队列
     * @param msg
     */
    @Override
    public void sendDelayedMessage(String msg,Map<Integer,Integer> map){
        // 将两个参数组合成一个 Map
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("msg", msg);
        messageMap.put("map", map);

        rabbitTemplate.convertAndSend("delayExchange", "delayRoutkey", messageMap, message -> {
            // 设置延迟时间
            message.getMessageProperties().getHeaders().put("x-delay", 300000L); // 300000 毫秒 = 5 分钟
            return message;
        });
    }

    /**
     * 回滚扣减库存
     * @param map
     */
    @Override
    public void HgReduceInventory(Map<Integer, Integer> map) {
        this.sendMessage("inventory","hgkc",map);
    }

}





